package ren.steve.system.utils;

import ren.steve.model.system.bean.SystemMenu;

import java.util.*;

/**
 * @Author: LiuGuoJia
 * @Description:
 * @Date: Created in 2024/1/19 15:00
 */

public class MenuNodeHelper<T> {

  public static List<SystemMenu> buildNode(List<SystemMenu> list) {
    List<SystemMenu> nodes = new ArrayList<>();
    for (SystemMenu menu : list) {
      if (Objects.equals(menu.getParentId(), "0")) {
        nodes.add(findChildren(menu, list));
      }
    }
    return cleanEmptyChildren(nodes);
  }

  public static SystemMenu findChildren (SystemMenu menu, List<SystemMenu> list) {
    for (SystemMenu item : list) {
      String id = menu.getId();
      String parentId = item.getParentId();
      if (Objects.equals(id, parentId)) {
        menu.getChildren().add(findChildren(item, list));
      }
    }
    return menu;
  }

  public static List<SystemMenu> cleanEmptyChildren (List<SystemMenu> list) {
    for (SystemMenu item : list) {
      if (item.getChildren().isEmpty()) {
        item.setChildren(null);
      } else {
        cleanEmptyChildren(item.getChildren());
      }
    }
    return list;
  }

  public static List<String> findParentIds (List<String> ids, SystemMenu menu, List<SystemMenu> menus) {
    if (Objects.equals(menu.getParentId(), "0")) {
      return ids;
    } else {
      for (SystemMenu item : menus) {
        if (Objects.equals(item.getId(), menu.getParentId())) {
          ids.add(item.getId());
          findParentIds(ids, item, menus);
        }
      }
    }
    return ids;
  }
}
